package com.cheyun.netsalev3.viewmodel

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.basedata.BaseDataParam
import com.cheyun.netsalev3.bean.basedata.Infotype
import com.cheyun.netsalev3.repository.AddClueActivityRepository
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.ToastUtil
import com.cheyun.netsalev3.view.AddSuccessActivity
import com.cheyun.netsalev3.view.CustomerTagActivity
import com.cheyun.netsalev3.view.EditClubActivity
import com.cheyun.netsalev3.view.choosecar.ChooseCarActivity
import com.cheyun.netsalev3.view.choosecity.ChooseCityActivity
import com.cheyun.netsalev3.view.cluefollowup.ClueFollowUpActivity
import com.cheyun.netsalev3.view.defeatdetails.DefeatDetailsActivity
import com.cheyun.netsalev3.view.mars.choosecar.MarsChooseCarActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.PopDialog
import com.cheyun.netsalev3.widget.TimePickerFragment
import com.jeremyliao.liveeventbus.LiveEventBus
import org.json.JSONObject
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList

class AddClueActivityViewModel(var editClueParam: EditClueParam,var come:String,var keliudata:Data?, var addClueActivityRepository: AddClueActivityRepository) : BaseViewModel(), PopDialog.PopDialogListener {
    var editBtnEnable = MutableLiveData<Boolean>()
    var focusable = MutableLiveData<Boolean>()
    var enableAdd = true
    //下次跟进时间距离当前时间天数
    var alarmday = 0
    //年月日
    var year = ""
    var month = ""
    var day = ""
    //下次沟通时间
    var remindetime = ObservableField<String>("")
    //下次沟通时间是否必填
    var remindetimeEnable = ObservableField<Boolean>(true)

    //显示战败
    var giveupcauseEnable = ObservableField<Boolean>(false)

    //到店时间
    var arrivetime = ObservableField<String>("")
    var showarrivetime = ObservableField<Boolean>(false)
    var tasktotal = ObservableField<String>("0")
    var showeffect = ObservableField<Boolean>(false)

    fun getFollowStatus(){
        var moth: (f: Followstate) -> Unit = {
            var temlist7 = ArrayList<NameIdParam>()
            it.followstate.forEach { d->  temlist7.add(NameIdParam(d.title, d.id))}
            gengjingzhuangtailist.postValue(temlist7)
        }
        var fail: () -> Unit = {
            editBtnEnable.postValue(true)
            enableAdd = true
        }
        addClueActivityRepository.getFollowStatus(editClueParam.effective,editClueParam.tid,moth,fail)
    }
    fun initTags(tags:List<Infotype>){
        var us = ArrayList<DialogParam>()
        var cs = ArrayList<DialogParam>()
        for(tag in tags){
            if(tag.rttype == 1)
                us.add(DialogParam(tag.title,tag.id.toString(),"1"))
            if(tag.rttype == 2)
                cs.add(DialogParam(tag.title,"0","0"))
        }
        userTag.postValue(us)
        customerOwnerTag.postValue(cs)
    }
    fun getFollowLevel(){
        var moth: (list: ClueLevel) -> Unit = {
            var temlist = ArrayList<NameIdParam>()
            if(it.connectway!=null) {
                it.connectway.forEach { d -> temlist.add(NameIdParam(d.title, d.id)) }
            }
            connectwaylist.postValue(temlist)
            var temlist2 = ArrayList<NameIdParam>()
            if(it.customerlevel!=null) {
                it.customerlevel.forEach { d -> temlist2.add(NameIdParam(d.title, d.ikey,0,d.alarmtime)) }
            }
            customerlevellist.postValue(temlist2)
            var temlist3 = ArrayList<NameIdParam>()
            if(it.next_connectway!=null) {
                it.next_connectway.forEach { d -> temlist3.add(NameIdParam(d.title, d.id)) }
            }
            ncwaylist.postValue(temlist3)
        }
        var fail: () -> Unit = {
            editBtnEnable.postValue(true)
            enableAdd = true
        }
        addClueActivityRepository.getlevel(editClueParam.followstate,editClueParam.tid,moth,fail)
    }

    fun add(view: View) {
        if (isPhoneParam != null) {
            showPop()
            return
        }
        if (editClueParam.uname.isNullOrBlank()) {
            MyToast( "请输入姓名")
            return
        }
        if (editClueParam.phone.isNullOrBlank()) {
            MyToast( "请输入手机号码")
            return
        }
//        if (!FunctionUtils.isPhone(editClueParam.phone, view.context)) {
//            return
//        }
        if (editClueParam.infoplacename.isNullOrBlank()) {
            MyToast( "请选择触点渠道")
            return
        }
        if (editClueParam.infotypename.isNullOrBlank()) {
            MyToast( "选择线索类型")
            return
        }
        if (editClueParam.infosourcename.isNullOrBlank()) {
            MyToast( "请选择信息来源")
            return
        }
        if(editClueParam.provincegroup.isNullOrBlank()){
            MyToast( "请选择用车城市")
            return
        }
        if(editClueParam.followstate.isNullOrBlank()){
            MyToast( "请选择跟进状态")
            return
        }
        if(editClueParam.customerlevel.isNullOrBlank()){
            MyToast( "请选择意向等级")
            return
        }
        if(giveupcauseEnable.get()!!){
            if (editClueParam.giveupcause.isNullOrBlank()) {
                MyToast("请选择战败原因")
                return
            }
            if (editClueParam.failurereason.isNullOrBlank()) {
                MyToast("请输入战败原因分析")
                return
            }
        }else{
            if(remindetimeEnable.get()!!) {
                if (editClueParam.remindetime.isNullOrBlank()) {
                    MyToast("请选择下次沟通时间")
                    return
                }
            }
        }

        if(editClueParam.connectway.isNullOrBlank()){
            MyToast( "请选择到店状态")
            return
        }
        if(editClueParam.followinfo.isNullOrBlank()){
            MyToast( "请输入沟通内容")
            return
        }
        if (editClueParam.brandgroup.isNullOrBlank()) {
            MyToast( "请选择首选车车系车型")
            return
        }
        var ut = userTag.value
        var et = customerOwnerTag.value
        var uts = arrayListOf<String>()
        var ets = arrayListOf<String>()
        if(ut!=null) {
            for (it in ut!!) {
                uts.add(it.id)
            }
            editClueParam.labels = uts.joinToString(",")
        }
        if(et!=null) {
            for (it in et!!) {
                ets.add(it.name)
            }
            editClueParam.userlabels = ets.joinToString(",")
        }
        editClueParam.nkey = "archive.purge"
        var withEffect = true
        if(editClueParam.tid.isNotEmpty()){
            edit(view)
        }else{
            var moth: (clueDetails: ClueDetails) -> Unit = {
                var intent = Intent(view.context, DefeatDetailsActivity::class.java)
                intent.putExtra("tid", it.tid)
                intent.putExtra("nkey","archive.index")
                view.context.startActivity(intent)
                myFinish();
            }
            var fail: () -> Unit = {
                editBtnEnable.postValue(true)
            }

            view.isEnabled = false
            addClueActivityRepository.editClue(editClueParam,moth,fail,withEffect)
        }

    }

    fun edit(view:View){
        var moth: () -> Unit = {
            MyToast( "提交成功")
            LiveEventBus.get().with("clueupdatge").postValue("")
            myFinish()
        }
        var fail: () -> Unit = {
            editBtnEnable.postValue(true)
        }
        view.isEnabled = false
        var withEffect = true
        if(showeffect.get()!! == false){
            withEffect = false
        }
        addClueActivityRepository.editClue2(editClueParam, moth,fail,withEffect)
    }


    var clickPositin: Positin? = null
    var baseDataParam: BaseDataParam? = MySharedPreferences.getBaseData()
    //小组数据
    var xzlist = MutableLiveData<List<NameIdParam>>()
    //信息渠道
    var xiqdlist = MutableLiveData<List<NameIdParam>>()
    //信息来源
    var xilylist = MutableLiveData<List<NameIdParam>>()
    //有效性
    var effectlist = MutableLiveData<List<NameIdParam>>()
    //客户类型
    var khlxlist = MutableLiveData<List<NameIdParam>>()
    //跟进状态
    var gengjingzhuangtailist = MutableLiveData<List<NameIdParam>>()
    //意向级别
    var customerlevellist = MutableLiveData<List<NameIdParam>>()
    //到店状态
    var connectwaylist = MutableLiveData<List<NameIdParam>>()
    //下次跟进方式
    var ncwaylist = MutableLiveData<List<NameIdParam>>()
    //战败原因
    var giveupcauselist = MutableLiveData<List<NameIdParam>>()

    var competitorListItem = MutableLiveData<List<KeyValueParam>>()

    //用户标签
    var userTag = MutableLiveData<List<DialogParam>>()
    //自定义标签
    var customerOwnerTag = MutableLiveData<List<DialogParam>>()

    var enableInfoplace = true
    var enableInfosource = true
    var enableInfotype = true

    enum class Positin {
        xz,  //线索类型
        xqd, //触点渠道
        xly, //信息来源
        effect,//有效性
        customer_owner_tag, //自定义标签
        gengjingzhuangtai,//跟进状态
        customerlevel,//意向级别
        connectway,//本次跟进方式（到店状态）
        next_connectway,//下次跟进方式
        giveupcause//战败原因
    }

    init {
        MySharedPreferences.getLoginData()?.member?.tasktotal?.apply {
            tasktotal.set(this)
        }

        if(editClueParam.tid.isNotEmpty() && !editClueParam.effective.equals("1")){
            showeffect.set(true)
        }
        baseDataParam?.apply {
            var temlist1 = ArrayList<NameIdParam>()
            //小组数据
            if(this.infotype!=null){
                for (item in this.infotype) {
                    temlist1.add(NameIdParam(item.title, item.id.toString()))
                }
            }
            xzlist.postValue(temlist1)
            var temlist2 = ArrayList<NameIdParam>()
            //信息渠道
            if(this.infoplace!=null){
                for (item in this.infoplace) {
                    if(item.readonly == 0) {
                        var isShow = true
                        if (this.infoplace_spids != null && this.infoplace_spids.size > 0) {
                            for (id in this.infoplace_spids) {
                                if (id == item.id) {
                                    isShow = false
                                }
                            }
                        }
                        if (item.ikey.equals("group")) {
                            isShow = false
                        }
                        if (isShow) {
                            temlist2.add(NameIdParam(item.title, item.id.toString()))
                        }
                    }
                }
            }
            xiqdlist.postValue(temlist2)
            var temlist3 = ArrayList<NameIdParam>()
            //信息来源
            if(this.infosource!=null){
                for (item in this.infosource) {
                    if(item.readonly == 0) {
                        temlist3.add(NameIdParam(item.title, item.id.toString()))

                        if (item.ikey.equals("adm")) {
                            if (editClueParam.infosource.equals(item.id.toString()))
                                enableInfosource = false
                        }
                    }
                }
            }
            xilylist.postValue(temlist3)

            var temlist4 = ArrayList<NameIdParam>()
            //有效性
            if(this.effective!=null){
                for (item in this.effective) {
                    temlist4.add(NameIdParam(item.title, item.id.toString()))
                }
            }
            effectlist.postValue(temlist4)
            //战败原因
            var temlist5 = ArrayList<NameIdParam>()
            if(this.giveupcause!=null){
                for (item in this.giveupcause) {
                    temlist5.add(NameIdParam(item.title, item.id.toString()))
                }
            }
            giveupcauselist.postValue(temlist5)

        }
        if(!editClueParam.competitor.isNullOrEmpty()){
            var cs = editClueParam.competitor.split(',')
            var ns = editClueParam.competitorname.split(',');
            var list = HashSet<KeyValueParam>()
            for(i in 0 until cs.size){
                if(ns.size<i) continue
                var item = KeyValueParam(ns.get(i),cs.get(i))
                item.idname = cs.get(i)
                list.add(item)
            }
            competitorListItem.postValue(list.toList())
        }
    }


    /**
     * 点击地区
     */
    fun onClickCity(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(content, ChooseCityActivity::class.java)
            content.startActivityForResult(intent, 103)
        }
    }
    //用户标签
    fun onEditUserTag(view:View){
        var ut = userTag.value
        if(ut!=null){
            var uts = arrayListOf<String>()
            for(it in ut!!){
                uts.add(it.id)
            }

            editClueParam.labels = uts.joinToString(",")
        }

        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(content, CustomerTagActivity::class.java)
            intent.putExtra("ids",editClueParam.labels)
            content.startActivityForResult(intent, 106)
        }
    }
    fun setUserTag(list:ArrayList<DialogParam>) {
        userTag.postValue(list)
    }
    fun removeUserTag(pos:Int) {
        var tags = userTag.value
        if(tags == null) {
            return
        }
        (tags as ArrayList).removeAt(pos)
        userTag.postValue(tags)
    }
    //自定义标签
    override fun onDialogSubmit(view: View,param:String){
        dialog?.dismiss()
        var tags = customerOwnerTag.value
        if(tags == null) {
            tags = ArrayList()
        }
        (tags as ArrayList).add(DialogParam(param,"0","0"))
        customerOwnerTag.postValue(tags)
    }

    fun removeCustomerEditTag(pos:Int){
        var tags = customerOwnerTag.value
        if(tags == null) {
            return
        }
        (tags as ArrayList).removeAt(pos)
        customerOwnerTag.postValue(tags)
    }

    fun setSex(i: Int) {
        editClueParam.sex = i.toString()
    }

    fun onClickNextFollowTime(view:View){
        var content = view.context
        if (content is AppCompatActivity) {
            activity = content

            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onDateSet
            val c = Calendar.getInstance()
            datePickerFragment.minDate = c.timeInMillis
            if (alarmday != 0) {
                c.add(Calendar.DAY_OF_MONTH, alarmday)
                datePickerFragment.maxDate = c.timeInMillis
            }
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }
    fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year = year.toString()
        this.month = month.toString()
        this.day = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSet
        timePickerFragment.show(activity?.supportFragmentManager!!, "timePicker")
    }
    fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        editClueParam.remindetime = FunctionUtils.formatTime(year, month, day, hourOfDay, minute)
        remindetime.set(editClueParam.remindetime)
    }

    fun onClickArrivetime(view:View){
        var content = view.context
        if (content is AppCompatActivity) {
            activity = content
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onArrivetimeDateSet
            val c = Calendar.getInstance()
            datePickerFragment.minDate = c.timeInMillis
            if (alarmday != 0) {
                c.add(Calendar.DAY_OF_MONTH, alarmday)
                datePickerFragment.maxDate = c.timeInMillis
            }
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }
    fun onArrivetimeDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year = year.toString()
        this.month = month.toString()
        this.day = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onArrivetimeTimeSet
        timePickerFragment.show(activity?.supportFragmentManager!!, "timePicker")
    }
    fun onArrivetimeTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        editClueParam.arrivetime = FunctionUtils.formatTime(year, month, day, hourOfDay, minute)
        arrivetime.set(editClueParam.arrivetime)
        editClueParam.followtime = editClueParam.arrivetime
    }

    private var dialog: PopDialog? = null

    /**
     * 小组数据
     */
    fun onClicShowPop(view: View, clickPositin: Positin) {
        //意向等级
        if(clickPositin == Positin.customerlevel){
            if(editClueParam.followstate.isEmpty()){
                //官网app来的线索不能修改
                MyToast("请先选择跟进状态")
                return
            }
        }
        //到店状态
        if(clickPositin == Positin.connectway){
            if(editClueParam.followstate.isEmpty()){
                //官网app来的线索不能修改
                MyToast("请先选择跟进状态")
                return
            }
        }
        //触点渠道
        if(clickPositin == Positin.xqd){
            if(!editClueParam.tid.equals("")){
                if(!enableInfoplace)
                    return
            }
        }
        //信息来源
        if(clickPositin == Positin.xly){
            if(!editClueParam.tid.equals("")){
                if(!enableInfosource)
                    return
            }
        }
        //触点渠道为主机厂（ikey=group）,线索类型为线上且不能更改
        if(clickPositin == Positin.xz){
            if(!editClueParam.tid.equals("")){
                if(!enableInfotype)
                    return
            }
        }
        if(clickPositin == Positin.customer_owner_tag){
//            dialogTitle.value = "添加标签"
//            dialogType.value = "edit"
        }
        this.clickPositin = clickPositin
        var content = view.context
        if (content is AppCompatActivity) {
            if (dialog == null) {
                dialog = PopDialog()
                dialog!!.listener = this
            }
            dialog?.show(content.supportFragmentManager, "pop")
        }
    }

    /**
     * 点击 品牌=0 车系=1车型=2
     */
    fun onClicCar(view: View, p: Int,requestCode:Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, MarsChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            intent.putExtra("Isspec",true)
            var car = CarBrandParam("", editClueParam.series, editClueParam.spec,"")
            car.brandname = editClueParam.ebrandname
            car.seriesname = editClueParam.eseriesname
            car.specname = editClueParam.especname
            intent.putExtra("car", car as Serializable)

            content.startActivityForResult(intent, requestCode)
        }
    }



    /**
     * 点击 现有品牌=0 车系=1
     */
    fun onClicCar2(view: View, p: Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, ChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            intent.putExtra("level",1)
            intent.putExtra("Isseries",true)
            var car = CarBrandParam(editClueParam.pbrand, editClueParam.pseries,"","")
            car.brandname = editClueParam.pbrandname
            car.seriesname = editClueParam.pseriesname
            intent.putExtra("car", car as Serializable)
            content.startActivityForResult(intent, 104)
        }
    }

    /**
     * 点击 现有品牌=0 车系=1
     */
    fun onClicCar3(view: View, p: Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, ChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            intent.putExtra("level",2)
            intent.putExtra("Isseries",true)
            var competitor = editClueParam.competitor
            var bid = ""
            var seriesId = ""
            if(competitor.isNotEmpty()){
                var ss = competitor.split("-")
                if(ss.size>0) bid = ss[0]
                if(ss.size>1) seriesId = ss[1]
            }
            var car = CarBrandParam(bid, seriesId,"","")
//            car.brandname = editClueParam.pbrandname
//            car.seriesname = editClueParam.pseriesname
            intent.putExtra("car", car as Serializable)
            content.startActivityForResult(intent, 105)
        }
    }

    //弹窗相关
    override var list: MutableLiveData<List<NameIdParam>>
        get() {
            when (clickPositin) {
                //小组数据
                Positin.xz -> {
                    return xzlist
                }
                //信息渠道
                Positin.xqd -> {
                    return xiqdlist
                }
                //信息来源
                Positin.xly -> {
                    return xilylist
                }
                //有效性
                Positin.effect -> {
                    return effectlist
                }

                Positin.gengjingzhuangtai -> {
                    return gengjingzhuangtailist
                }
                Positin.customerlevel -> {
                    return customerlevellist
                }
                Positin.connectway -> {
                    return connectwaylist
                }
                Positin.next_connectway -> {
                    return ncwaylist
                }
                Positin.giveupcause ->{
                    return giveupcauselist
                }

            }
            return MutableLiveData<List<NameIdParam>>()
        }
        set(value) {
            list = value
        }
    override var dialogType: MutableLiveData<String>
        get() {
            if(clickPositin == Positin.customer_owner_tag){
                return MutableLiveData("edit")
            }else{
                return MutableLiveData("list")
            }
        }
        set(value) {
            dialogType = value
        }
    override var dialogTitle: MutableLiveData<String>
        get() {
            if(clickPositin == Positin.customer_owner_tag){
                return MutableLiveData("添加标签")
            }else{
                return MutableLiveData("请选择")
            }
        }
        set(value) {
            dialogTitle = value
        }

    override fun onClickItem(view: View, param: NameIdParam) {
//        focusable.postValue(false)
        when (clickPositin) {
            //小组数据
            Positin.xz -> {
                xzlist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.infotypename = param.name
                editClueParam.infotype = param.id.toString()
            }
            //信息渠道
            Positin.xqd -> {
                xiqdlist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.infoplacename = param.name
                editClueParam.infoplace = param.id.toString()

                //根据触点渠道自动设置线索类型
                baseDataParam?.apply {
                    var infoType:String  = ""
                    for(item in this.infoplace){
                        if(item.id.toString().equals(param.id)){
                            infoType = item.settings.infotype
                        }
                    }
                    var temlist1 = ArrayList<NameIdParam>()
                    //小组数据
                    if(this.infotype!=null){
                        for (item in this.infotype) {
                            if(item.id.toString() == infoType){
                                temlist1.add(NameIdParam(item.title, item.id.toString()))
                                editClueParam.infotypename = item.title
                                editClueParam.infotype = item.id.toString()
                            }
                        }
                    }
                    xzlist.postValue(temlist1)
                }

            }
            //信息来源
            Positin.xly -> {
                xilylist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.infosourcename = param.name
                editClueParam.infosource = param.id.toString()
            }
            //有效性
            Positin.effect -> {
                effectlist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.effectivename = param.name
                editClueParam.effective = param.id.toString()
            }
            Positin.gengjingzhuangtai ->{
                gengjingzhuangtailist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.followstatename = param.name
                editClueParam.followstate = param.id.toString()
                getFollowLevel()
                //跟进状态followstate=2608（邀约失败）和2612（锁单失败）时需要新增 giveupcause（战败原因）和failurereason（失败原因分析）两个字段
                if(param.id.equals("2608") || param.id.equals("2612")){
                    giveupcauseEnable.set(true)
                }else
                    giveupcauseEnable.set(false)
            }
            Positin.customerlevel ->{
                customerlevellist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.customerlevelname = param.name
                editClueParam.customerlevel = param.id
                if(param.value!=null && param.value!!.isNotEmpty()){
                    //回填下次沟通时间
                    remindetime.set(param.value)
                    editClueParam.remindetime = param.value!!
                }else{
                    remindetimeEnable.set(false)
                }
            }
            Positin.connectway ->{
                connectwaylist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.connectwayname = param.name
                editClueParam.connectway = param.id.toString()
                //到店
                if(!param.id.equals("3")){
                    showarrivetime.set(false)
                    editClueParam.followtime = CommonFunc.getCurrentFullDate()
                }else{
                    showarrivetime.set(true)
                }
            }
            Positin.next_connectway ->{
                ncwaylist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.ncwayname = param.name
                editClueParam.ncway = param.id.toString()
            }
            Positin.giveupcause ->{
                giveupcauselist.value?.apply {
                    for (item in this) {
                        item.IsSelect = param.id == item.id
                    }
                }
                editClueParam.giveupcausename = param.name
                editClueParam.giveupcause = param.id.toString()
            }
        }
        dialog?.dismiss()
    }

    /**
     * 设置意向车系车型
     */
    fun setYixiangCarData(carBrandParam: CarBrandParam) {
        editClueParam.brandgroup = carBrandParam.series+","+carBrandParam.spec
//        editClueParam.seriesname = carBrandParam.seriesname
//        editClueParam.series = carBrandParam.series
//        editClueParam.specname = carBrandParam.specname
//        editClueParam.spec = carBrandParam.spec
    }
    /**
     * 设置备选车系车型
     */
    fun setBeixuanCarData(carBrandParam: CarBrandParam) {
        editClueParam.secssgroup = carBrandParam.series+","+carBrandParam.spec
//        editClueParam.seriesname = carBrandParam.seriesname
//        editClueParam.series = carBrandParam.series
//        editClueParam.specname = carBrandParam.specname
//        editClueParam.spec = carBrandParam.spec
    }

    /**
     * 设置汽车品牌
     */
    fun setCarData(carBrandParam: CarBrandParam) {
        editClueParam.ebrandname = carBrandParam.brandname
//        editClueParam.brand = carBrandParam.brand
        editClueParam.eseriesname = carBrandParam.seriesname
        editClueParam.series = carBrandParam.series
        editClueParam.especname = carBrandParam.specname
        editClueParam.spec = carBrandParam.spec
    }

    /**
     * 设置汽车品牌2
     */
    fun setCarData2(carBrandParam: CarBrandParam) {
        editClueParam.pbrandname = carBrandParam.brandname
        editClueParam.pbrand = carBrandParam.brand
        editClueParam.pseriesname = carBrandParam.seriesname
        editClueParam.pseries = carBrandParam.series
    }

    /**
     * 设置城市
     */
    fun setCityData(show: String, id: String) {
        editClueParam.cityname = show
        editClueParam.provincegroup = id
    }

    override fun onCleared() {
        super.onCleared()
        activity = null
    }

    var isPhoneParam: IsPhoneParam? = null
    var activity: AppCompatActivity? = null
    /**
     * 检查电话号码是否存在
     */
    fun getPhone(phone: String, context: AppCompatActivity) {
        this.activity = context
        isPhoneParam = null
        var moth: (item: IsPhoneParam) -> Unit = {
            if (it.state == "n") {
                var show = true
                if (it != null && !it!!.revkey.isNullOrEmpty()) {
//                    if(it!!.revkey.equals("bazaar") || it!!.revkey.equals("owner")|| it!!.revkey.equals("check")){
//                        show = false
//                        MyToast(it!!.msg)
//                    }
                    //2020-04-22  线索从线索池导入后，如果线索在“审核管理”模块，同“战败管理”线索处理机制一样激活，重新分配
                    if(it!!.revkey.equals("bazaar") || it!!.revkey.equals("owner")){
                        show = false
                        MyToast(it!!.msg)
                    }
                }
                if(show) {
                    isPhoneParam = it
                    showPop()
                }
            }

        }
        addClueActivityRepository.IsPhone(phone, moth)
    }

    /**
     *显示弹窗
     */
    fun showPop() {
        isPhoneParam?.apply {
            activity?.apply {
                var dialog = MyContentDialog.newInstance("提示", isPhoneParam!!.msg)
                dialog.onClickOk = this@AddClueActivityViewModel::onClickOk
                dialog.show(this.supportFragmentManager, "")
            }
        }
    }

    /**
     * 点击弹窗ok
     */
    fun onClickOk() {
        activity?.apply {
            if (isPhoneParam != null && !isPhoneParam!!.revkey.isNullOrEmpty()) {
                var intent = Intent(this, DefeatDetailsActivity::class.java)

                if(isPhoneParam!!.tid.isNullOrEmpty()){
                    intent.putExtra("revkey", isPhoneParam!!.revkey)
                }else {
                    intent.putExtra("tid", isPhoneParam!!.tid)
                }

                if(isPhoneParam!!.revkey.equals("follow") || isPhoneParam!!.revkey.equals("followtip")){
                    intent.putExtra("nkey", "archive.purge")  // 跟进，订车，线索移交
                }else{
                    intent.putExtra("nkey", "archive.index")
//                    intent.putExtra("nkey", "archivepot.index")  // 拨号，激活
                    intent.putExtra("revkey", isPhoneParam!!.revkey)
                }
                if(keliudata!=null){
                    intent.putExtra("keliudata", keliudata!! as Serializable)
                }
                intent.putExtra("come", come)
                this.startActivity(intent)
            }
        }
    }

    lateinit var mActivity:Activity
    fun setActivity(mContext:Activity){
        mActivity = mContext;
    }

    fun addCompetitor(carBrandParam: CarBrandParam) {
        var name = carBrandParam.brandname + "-" + carBrandParam.seriesname
        var value = carBrandParam.brand+"-"+carBrandParam.series
        editClueParam.competitor = value

//        if(editClueParam.competitor.contains(value)){
//            MyToast( "已添加该品牌车系")
//            return;
//        }
//        var list = HashSet<KeyValueParam>()
//        competitorListItem.value?.apply {
//            list.addAll(this)
//        }
//        if (list.size >= 5) {
//            MyToast( "最多只能增加5个品牌车系")
//            return
//        }
//
//        var item = KeyValueParam(name,value)
//        item.idname = value
//        list.add(item)
//        competitorListItem.postValue(list.toList())
//        if(editClueParam.competitor.length>0)
//            editClueParam.competitor += ","
//        editClueParam.competitor += value

//        this.activity
//        if(mActivity!=null){
//            (mActivity as EditClubActivity).changeLayoutHeight(1,list.size);
//        }
    }

    /**
     * 添加线索标签
     */
    fun addTagItem(param:NameIdParam) {

    }

    /**
     * 添加线索标签
     */
    fun addOffTagItem(param:NameIdParam) {

    }

    /**
     * 删除竞品item
     */
    fun onDelCompetitor(view: View, item: KeyValueParam, position: Int) {
        var list = HashSet<KeyValueParam>()
        competitorListItem.value?.apply {
            list.addAll(this)
            list.remove(item)
        }
        competitorListItem.postValue(list.toList())
        list.apply {
            editClueParam.competitor = ""
            for(info in this){
                if(editClueParam.competitor.length>0)
                    editClueParam.competitor += ","
                editClueParam.competitor += info.value
            }
        }
//        if(mActivity!=null){
//            (mActivity as EditClubActivity).changeLayoutHeight(1,list.size);
//        }
    }

    /**
     * 删除标签item
     */
    fun onDelTag(view: View, item: KeyValueParam, position: Int) {

    }

    /**
     * 删除标签item
     */
    fun onDelOffTag(view: View, item: KeyValueParam, position: Int) {


    }

}